import { PageContainer } from '@ant-design/pro-layout';
import { Spin,message, Drawer,Table} from 'antd';
import ProTable from '@ant-design/pro-table';
import React, { useState,useRef} from 'react';
import type { ProColumns,ActionType} from '@ant-design/pro-table';
import {WarehouseType,ProductType} from '../../../model';
import {deliveryDataList,invoiceDetailListData,updateInvoiceIsBill,exportDelivery,orderDetailDataById,ticketDataByDealerId,withdraw} from '../service';
import { exportFile, manufacturerOption } from '@/utils/utils';
import { Row,Col,Button,Space } from 'antd';
import UpDownLabel from '@/components/Common/UpDownLabel';
import {moneyFormat,moneyFormat2} from '@/utils/utils';
import { Upload } from 'antd';
import { Popconfirm } from 'antd';
import html2canvas from 'html2canvas';

export default () => {
const formRef = useRef<ActionType>();

const [showDetail,setShowDetail]  = useState(false);
const [spinningFlag,setSpinningFlag]  = useState(false);
const [detailFlag,setDetailFlag]  = useState(false);
const [initData,setInitData] = useState<any>({});
const [dealerCode,setDealerCode] =  useState("");
const [orderNumber,setOrderNumber] =  useState(""); 
const [ticketId,setTicketId] =  useState(""); 

const [ticket,setTicket] = useState<any>({});
const [proData,setProDate]  = useState([]);
const [activeKey,setActiveKey] = useState("tab1");
 //表头信息以及表值设置
 const pColumns: ProColumns<ProductType>[] = [
 
  {
    title: '产品名称',
    dataIndex: 'product_name',
    editable:false,
    renderText:(_,record:any)=>{
      if(record.is_gifts==1){
        return `${record.product_name}(赠品)`
      }
      return record.product_name;
    }
  },
  {
    title: '产品型号',
    dataIndex: 'product_standard',
    editable:false,
  },
  {
    width:50,
    title: '单位',
    dataIndex: 'packing_unit',
    hideInSearch:true,
    editable:false,
  },
  {
    title: '产品批号',
    dataIndex: 'batch',
    editable:false,
  },
  {
    title: '失效日期',
    dataIndex: 'validity',
    editable:false,
  },
  {
    width:100,
    title: '发货数量',
    dataIndex: 'numbs',
    editable:false,
  },
  {
    width:100,
    title: '收货数量',
    dataIndex: 'received_numbs',
    editable:false,
  },
  // {
  //   width:100,
  //   title: '退货数量',
  //   dataIndex: 'return_numbs',
  //   editable:false,
  // }
  {
    title: '备注',
    dataIndex: 'remarks',
    width:100,
    ellipsis:true
  },
];

  //表头信息以及表值设置
  const columns: ProColumns<WarehouseType>[] = [
    
    {
      title:'发货单号',
      dataIndex: 'invoiceNo',
      width:180,
      ellipsis:true,
      fieldProps:{
        onPressEnter:  ()=> {
          this.formRef?.current?.submit();
      }}
    },
    {
      title:'订单号',
      hideInSearch:true,
      dataIndex: 'order_number',
      width:180,
      ellipsis:true,
      fieldProps:{
        onPressEnter:  ()=> {
          this.formRef?.current?.submit();
      }}
    },
    {
      title: '发货日期',
      dataIndex: 'sendTime',
      ellipsis:true,
      width:100,
      hideInSearch:true
    },
    {
      title: '客户代码',
      dataIndex: 'dealerCode',
      width:100,
      ellipsis:true,
      fieldProps:{
        onPressEnter:  ()=> {
          this.formRef?.current?.submit();
      }}
    },
    {
      title: '客户名称',
      dataIndex: 'dealerName',
      width:250,
      ellipsis:true,
      fieldProps:{
        onPressEnter:  ()=> {
          this.formRef?.current?.submit();
      }}
    },
    {
      title:'运单号',
      dataIndex: 'waybillNo',
      width:250,
      ellipsis:true,
      fieldProps:{
        onPressEnter:  ()=> {
          this.formRef?.current?.submit();
      }}
    },
    {
      title:'发货日期',
      valueType:'dateRange',
      ellipsis:true,
      dataIndex: 'date',
      hideInTable:true,
    },
    {
      title: '开票状态',
      dataIndex: 'isBill',
      valueType:'select',
      width:80,
      ellipsis:true,
      valueEnum:{
        0:{text:'未开'},
        1:{text:'已开'}
      },
      renderText:v=>v==='0'?'未开':'已开'
    },
    {
      title: "操作",
      valueType: 'option',
      fixed:'right',
      width:100,
      render: (text, record:any,_, action) => [
        <a
        key="rect"
        onClick={async() => {
          setSpinningFlag(true);
          var param :any= {"invoiceId":record.id}
          if(activeKey==='tab1'){
            param.isWithdraw = "0";
          }else{
            param.isWithdraw = "1";
          }
          var val=await invoiceDetailListData(param);
          if(val.errorCode==="200"){
            setProDate(val.data);
            setTicketId(record.id);
            setOrderNumber(record.order_number);
          }else{
            message.error("获取订单信息失败");
            setSpinningFlag(false);
            return;
          }

          var val=await ticketDataByDealerId({"dealerId":record.dealerId});
          if(val.errorCode==="200"){
            console.log(val);
            setShowDetail(true);
            setTicket(val.data);
          }else{
            message.error("获取订单信息失败");
            setSpinningFlag(false);
          }
          setSpinningFlag(false);
        }}
      >
        详情
      </a>
    ]
    }
  ];


    //表头信息以及表值设置
   const pcolumns: ProColumns<ProductType>[] = [
     
      {
        title: '产品名称',
        dataIndex: 'product_name',
        renderText:(_,record:any)=>{
          if(record.is_gifts==1){
            return `${record.product_name}(赠品)`
          }
          return record.product_name;
        }
      },
      {
        title: '产品型号',
        dataIndex: 'product_standard',
      },
      {
        title: '单位',
        dataIndex: 'packing_unit',
      },
      {
        title: '订货数量',
        dataIndex: 'numbs',
      },
      {
        title: '单价(元)',
        valueType:'money',
        dataIndex: 'standard_price',
        render:(_,record:any)=>{
          if(record.is_gifts==1){
            return `0`
          }
          if(record.unit_price&&Number(record.unit_price)!=Number(record.standard_price)){
            return <>{moneyFormat(record.standard_price)}<span style={{textDecoration:'line-through',color:'#d1d1d1',marginLeft:10}}>{moneyFormat(record.unit_price)}</span></>
          }
          return moneyFormat(record.standard_price);
        }
      },
      {
        title: '已发货',
        dataIndex: 'send_numbs',
      },
      {
        title: '金额(元)',
        valueType:'money',
        align:'left',
        dataIndex: 'actual_amount',
      },

    ];

  const actionRef = useRef<ActionType>();

  const handlePreview = async (file:any) => {
    window.open(file.url);
   };


   const printOrder=()=>{
    console.log("调用打印");
    const el:any = document.getElementById('billDetails');
    // window.pageYoffset = 0;
    var scrollTop = document.documentElement.scrollTop;
    document.documentElement.scrollTop = 0;
    // document.body.scrollTop = 0;
    const win:any = window.open('','printwindow');
    html2canvas(el,{useCORS: true,}).then(canvas => {
      win.document.body.appendChild(canvas);
      win.print();
      win.close();
      document.documentElement.scrollTop = scrollTop
    });
  }

  const updateInvoice=async(isBill:string,ids:any)=>{
    setSpinningFlag(true);
    ids = ids.join(',');
    var val = await updateInvoiceIsBill({'isBill':isBill,'ids':ids});
    if(val.errorCode==='200'){
      actionRef.current?.reloadAndRest?.();
    }else{
      message.error(val.errorMessage);
    }
    setSpinningFlag(false);
  }

  return (
    <PageContainer>
    <ProTable
      scroll={{x:1200}}
      actionRef={actionRef}
      formRef = {formRef}
      request={(params, sorter, filter) =>{
        if(params.date){
          params.beginDate=params.date[0];
          params.endDate=params.date[1];
          params.date=undefined;
        }
        // params.beginDate='2022-05-06';
        if(activeKey==='tab1'){
          params.isWithdraw = "0";
        }else{
          params.isWithdraw = "1";
        }
        return deliveryDataList({...params,filter});
      } }
      tableAlertOptionRender={({selectedRowKeys,onCleanSelected}) => {
        return (
          <Space size={16}>
            <a key="i2" style={{ marginLeft: 8 }} onClick={onCleanSelected}>
              取消选择
            </a>
            <a key="i1" onClick={()=>{
              updateInvoice("1",selectedRowKeys);
            }}>已开票</a>
            <a key="i0" onClick={()=>{
              updateInvoice("0",selectedRowKeys);
            }}>未开票</a>
          </Space>
        );
      }}
      rowSelection={{
        selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
      }}
      columns={columns}
      rowKey="id"
      search={{
        span: 6,
        defaultCollapsed:false,
        collapseRender:false,
        optionRender: ({ searchText, resetText }, { form }) => [
          <Button
            key="search"
            type="primary"
            onClick={() => {
              form?.submit();
            }}
          >
            {searchText}
          </Button>,
          <Button
            key="rest"
            onClick={() => {
              form?.resetFields();
              form?.submit();
            }}
          >
            {resetText}
          </Button>,
          <Button key="out" onClick={async()=>{
            setSpinningFlag(true);
            var date = form?.getFieldValue("date");
            var params:any={};
            if(date){
              params.beginDate=date[0].format('YYYY-MM-DD');
              params.endDate=date[1].format('YYYY-MM-DD');
              params.date=undefined;
            }
            params.invoiceNo=form?.getFieldValue("invoiceNo");
            params.dealerName= form?.getFieldValue("dealerName");
            params.dealerCode= form?.getFieldValue("dealerCode");
            params.waybillNo= form?.getFieldValue("waybillNo");
            params.isBill= form?.getFieldValue("isBill");
            params.manufacturer= form?.getFieldValue("manufacturer");
            var val = await exportDelivery(params);
            if(val.errorCode==='200'){
              exportFile(val.data,'发货单.xlsx')
            }else{
              message.error(val.errorMessage);
            }
            setSpinningFlag(false);
          }}>导出</Button>,
        ],
      }}
      pagination={{
        pageSizeOptions:['20', '100', '500']
      }}
      toolbar={{
        menu: {
          type: 'tab',
          activeKey: activeKey,
          items: [
            {
              key: 'tab1',
              label: <span>发货单</span>,
            },
            // {
            //   key: 'tab2',
            //   label: <span>已撤回</span>,
            // },
          ],
          onChange: (key) => {
            setActiveKey(key as string);
            actionRef.current?.reloadAndRest?.();
          },
        },
        settings: [],
      }}
      />
         <Drawer
            title="详情"
            visible={showDetail}
            width={1200}
            onClose={()=>setShowDetail(false)}>
            <Row>
              <Col span={15}></Col>
              <Col span={4} hidden={activeKey==='tab2'}>
                {/* <Popconfirm title="确定要撤回吗?" key="delete" onConfirm={async() => {
                   setSpinningFlag(true);
                   var params = {id:ticketId};
                   var val = await withdraw(params);
                   if(val.errorCode==='200'){
                      message.success('撤回成功');
                      setShowDetail(false);
                      actionRef.current?.reloadAndRest?.();
                   }else{
                      message.error(val.errorMessage);
                   }
                   setSpinningFlag(false);
                }}>
                  <Button type="primary" hidden={sessionStorage.getItem('access')==='wbsc'}>发货单撤回</Button>
                </Popconfirm> */}
              </Col>
              <Col span={1}>
              </Col>
              <Col span={4}>
                <Button type="primary" onClick={printOrder} >打印</Button>
              </Col>
            </Row>
            <div id="billDetails">
              <Row>
                <Col><UpDownLabel title="订单号" texts={[orderNumber]}/></Col>
              </Row>
              <Row>
                <Col span={6}><UpDownLabel title="开户名称" texts={[ticket?.account_name]}/></Col>
                <Col span={6}><UpDownLabel title="税号" texts={[ticket?.duty_paragraph]}/></Col>
                <Col span={6}><UpDownLabel title="一般纳税人" texts={[ticket?.isTaxpayer==1?"是":"否"]}/></Col>
                <Col span={6}><UpDownLabel title="发票类型" texts={[ticket?.invoice_type==='1'?"专票":"普票"]}/></Col>
              </Row>
              <Row>
                <Col span={6}><UpDownLabel title="开户银行" texts={[ticket?.bank]}/></Col>
                <Col span={6}><UpDownLabel title="银行账号" texts={[ticket?.bank_account]}/></Col>
                <Col span={6}><UpDownLabel title="开票电话" texts={[ticket?.invoice_phone]}/></Col>
                <Col span={6}><UpDownLabel title="开票地址" texts={[ticket?.invoice_address]}/></Col>
              </Row>
              <Row>
                <Col span={6}><UpDownLabel title="收件人" texts={[ticket?.recipient]}/></Col>
                <Col span={6}><UpDownLabel title="收件人电话" texts={[ticket?.recipient_phone]}/></Col>
                <Col span={6}><UpDownLabel title="邮箱地址" texts={[ticket?.mail]}/></Col>
                <Col span={6}><UpDownLabel title="收件地区" texts={[ticket?.provinces_label+'/'+ticket?.city_label+'/'+ticket?.area_label]}/></Col>
              </Row>
              <Row>
                <Col span={24}><UpDownLabel title="寄票详细地址" texts={[ticket?.send_address]}/></Col>
              </Row>
              <ProTable<ProductType>
                headerTitle="产品列表"
                rowKey="id"
                dataSource={proData}
                toolBarRender={false}
                columns={pColumns}
                search={false}
                toolbar={{settings:[]}}
                pagination={false}
            ></ProTable>
           </div>
         </Drawer>

         <Drawer
            destroyOnClose={true}
            width={1200}
            title={"详情"}
            visible={detailFlag}
            onClose={()=>{setDetailFlag(false)}}
          >
          <div>
          <Row style={{marginLeft:"22px"}}>
            <Col span={5}><UpDownLabel title="订单号" texts={[initData?.order?.order_number]}/></Col>
            <Col span={5}><UpDownLabel title="客户代码" texts={[dealerCode]}/></Col>
            <Col span={5}><UpDownLabel title="客户名称" texts={[initData?.order?.dealerName]}/></Col>
            <Col span={5}><UpDownLabel title="订货日期" texts={[initData?.order?.order_time]}/></Col>
            <Col span={4}><UpDownLabel title="交货日期	" texts={[initData?.order?.delivery_time]}/></Col>
          </Row>
          <Row style={{marginLeft:"22px"}}>
            <Col span={5}><UpDownLabel title="付款方式" texts={[initData?.order?.payment_method]}/></Col>
            <Col span={5}><UpDownLabel title="运费方式" texts={[initData?.order?.postPayMethod]}/></Col>
            <Col span={5}><UpDownLabel title="销售" texts={[initData?.order?.salesName]}/></Col>
            <Col span={5}><UpDownLabel title="收货人" texts={[initData?.order?.consignee]}/></Col>
            <Col span={4}><UpDownLabel title="收货电话" texts={[initData?.order?.mobile]}/></Col>
          </Row>
          <Row style={{marginLeft:"22px"}}>
            <Col span={24}><UpDownLabel title="收货地址" texts={[initData?.order?.provinces_label+initData?.order?.city_label+initData?.order?.area_label+' - '+initData?.order?.delivery_address]}/></Col>
          </Row>
          <ProTable<ProductType>
              headerTitle='订单产品'
              size="small"
              toolbar={{ settings: [] }}
              columns={pcolumns}
              dataSource={initData?.list}
              rowKey="id"
              pagination={false}
              search={false}
              summary={pageData => {      
                return (
                  <>
                    <Table.Summary.Row>
                      <Table.Summary.Cell index={1} colSpan={7}>总金额:</Table.Summary.Cell>
                      <Table.Summary.Cell index={1} align='left'>
                      ￥{moneyFormat(initData?.order?.total)}
                      </Table.Summary.Cell>
                    </Table.Summary.Row>
                    <Table.Summary.Row>
                      <Table.Summary.Cell index={1} colSpan={7}>优惠金额:</Table.Summary.Cell>
                      <Table.Summary.Cell index={1} align='left'>
                      ￥{moneyFormat2(initData?.order?.discount)}
                      </Table.Summary.Cell>
                    </Table.Summary.Row>
                    <Table.Summary.Row>
                      <Table.Summary.Cell index={1} colSpan={7}>返利金额:</Table.Summary.Cell>
                      <Table.Summary.Cell index={1} align='left'>
                      ￥{moneyFormat2(initData?.order?.use_rebate)}
                      </Table.Summary.Cell>
                    </Table.Summary.Row>
                    <Table.Summary.Row>
                      <Table.Summary.Cell index={1} colSpan={7}>实付金额:</Table.Summary.Cell>
                      <Table.Summary.Cell index={1} align='left' >
                      ￥{moneyFormat(initData?.order?.actual_amount)}
                      </Table.Summary.Cell>
                    </Table.Summary.Row>
                  </>
                );
              }}
            >
          </ProTable>

          <Row style={{margin:"22px"}}>
            <Col span={24}><UpDownLabel title="备注" texts={[initData?.order?.remarks]}/></Col>
          </Row>
          </div>

          <Row style={{margin:"22px 0"}}>
            <Upload   fileList={initData?.attList}  onPreview={handlePreview} showUploadList={{showRemoveIcon:false}}
            >
            </Upload>
          </Row>
        </Drawer>

         <Spin spinning={spinningFlag} style={{transform:'translate(-50%,-50%)',left:'50%',top:'50%',position:'absolute'}}/>
  </PageContainer>
  );
};